package top.lshaci.learning.netty.websocket;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelId;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

/**
 * WebSocketServerHandler
 *
 * @author lshaci
 * @since 1.0.0
 */
public class WebSocketServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    private static final Log log = LogFactory.get(WebSocketServerHandler.class);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        log.debug("服务器收到消息: {}", msg.text());
        String content = StrUtil.format("服务器时间 {}: {}", DateTime.now(), msg.text());
        ctx.writeAndFlush(new TextWebSocketFrame(content));
    }

    /**
     * 当 web 客户端连接后，触发方法
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        ChannelId id = ctx.channel().id();
        log.debug("handlerAdded 被调用, id => LongText: {}", id.asLongText());
        log.debug("handlerAdded 被调用, id => ShortText: {}", id.asShortText());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        ChannelId id = ctx.channel().id();
        log.debug("handlerRemoved 被调用, id => LongText: {}", id.asLongText());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ChannelId id = ctx.channel().id();
        log.error(cause, "exceptionCaught 被调用, id => LongText: {}", id.asLongText());
        ctx.close();
    }
}
